#include "bearpi_h2821.h"



bearpi_h2821::bearpi_h2821(const std::string& work_mode)
{
    at_parser = new at_cmd_parser("/dev/ttyUSB0");

    if(nullptr != at_parser)
    {
        if(work_mode == "SERVER")this->h2821_start_server();    //启动服务端
        else if(work_mode == "CLIENT")this->h2821_start_client();    //启动客户端
        else{}
    }
    
}

bearpi_h2821::~bearpi_h2821()
{
    if(nullptr != at_parser)
    {
        at_parser->stop();
        delete at_parser;
        at_parser = nullptr;
    }
}


/* 通用的 AT 指令 */
//AT测试命令
int bearpi_h2821::at_cmd(void)
{
    if(nullptr == at_parser)return -1;

    at_parser->send_at_cmd("AT");
    return 0;
}

//ATE命令，0-关闭回显，1-打开回显
int bearpi_h2821::ate_cmd(char flag)
{
    if(nullptr == at_parser)return -1;

    if(flag)at_parser->send_at_cmd("ATE1");
    else at_parser->send_at_cmd("ATE0");

    return 0;
}

//重启设备
int bearpi_h2821::at_reset(void)
{
    if(nullptr == at_parser)return -1;

    at_parser->send_at_cmd("AT+RESET");

    return 0;
}

//恢复出厂设置
int bearpi_h2821::at_restore(void)
{
    if(nullptr == at_parser)return -1;

    at_parser->send_at_cmd("AT+RESTORESET");

    return 0;
}

//配置串口参数
int bearpi_h2821::at_uart_config(unsigned int baudrate, char databits, char stopbits, char parity, char flow_ctrl)
{
    if(nullptr == at_parser)return -1;

    return 0;
}

//设置发射功率
int bearpi_h2821::at_set_txpower(char pwr_value)
{
    if(nullptr == at_parser)return -1;

    return 0;
}

//设置mac地址
int bearpi_h2821::at_set_mac(const std::string& mac_addr)
{
    if(nullptr == at_parser)return -1;
    if(mac_addr.empty())return -1;

    std::string cmd = "AT+SETSLEADDR=" + mac_addr;

    at_parser->send_at_cmd(cmd);

    return 0;
}

//设置模组的工作模式
int bearpi_h2821::at_set_mode(char work_mode)
{
    if(nullptr == at_parser)return -1;

    if(work_mode)at_parser->send_at_cmd("AT+SETMODE=1");
    else at_parser->send_at_cmd("AT+SETMODE=0");
    
    return 0;
}   


/**
 * 设置服务端相关指令
 */
//设置服务端名字
int bearpi_h2821::at_s_set_name(const std::string& name)
{
    if(nullptr == at_parser)return -1;
    if(name.empty())return -1;

    std::string cmd = "AT+SSETNAME=" + name;

    at_parser->send_at_cmd(cmd);

    return 0;
} 

//开启服务端服务
int bearpi_h2821::at_start_server(char enable, char encry, const std::string& secret_key)
{
    if(nullptr == at_parser)return -1;

    std::string cmd;

    if(enable)
    {
        if((encry == 1) && (!secret_key.empty()))
        {
            cmd = "AT+SSERVER=1,1,";
            cmd.append(secret_key);
        }
        else cmd = "AT+SSERVER=1";
    }
    else
    {
        cmd = "AT+SSERVER=0";
    }


    at_parser->send_at_cmd(cmd);

    return 0;
}

//服务端获取用户连接列表
int bearpi_h2821::at_s_client_list()
{
    if(nullptr == at_parser)return -1;

    std::string cmd = "AT+SCLIST";

    at_parser->send_at_cmd(cmd);

    return 0;
}

//服务端向客户端发送数据
int bearpi_h2821::at_s_send_data(std::string& client, std::string& data_str)
{
    int send_len = 0;
    std::string cmd_str;


    if((!client.empty()) && (!data_str.empty()))
    {
        cmd_str = "AT+SSEND=";
        cmd_str.append(client);
        cmd_str.append(",");
        cmd_str.append(data_str);

        at_parser->send_at_cmd(cmd_str);
        send_len = static_cast<int>(data_str.size());
        
    } 
    else send_len = 0;
    
    return send_len;
}

//服务端向所有客户端发送数据
int bearpi_h2821::at_s_send_data(std::string& data_str)
{
    int send_len = 0;
    std::string cmd_str;

    if(!data_str.empty())
    {
        cmd_str = "AT+SSENDALL=";
        cmd_str.append(data_str);
        at_parser->send_at_cmd(cmd_str);
        send_len = static_cast<int>(data_str.size());
        
    } 
    else send_len = 0;
    
    return send_len;
}


/**
 * 静态函数，用于AT指令回调
 */

//接收到OK回复
int bearpi_h2821::server_ok_handler(const std::string& response)
{
    std::cout << ">>> server_ok_handler >>>" << response << std::endl;

    return 0;
}

//接收到数据
int bearpi_h2821::server_recv_process(const std::string& response)
{
    //std::cout << ">>> server_recv_process >>>" << response << std::endl;

    {
        //使用 lock_guard 自动管理互斥锁，获取服务端接收互斥锁
        std::lock_guard<std::mutex> lock(srv_recv_mtx);
        srv_recv_queue.push(response);
    }    //退出作用域，解锁
    srv_cv.notify_one();  // 唤醒处理线程
   
    return 0;
}

//接收到+SETMODE
int bearpi_h2821::server_set_mode_handler(const std::string& response)
{
    std::cout << ">>> server_set_mode_handler >>>" << response << std::endl;

    return 0;
}

//接收到+SETADDR
int bearpi_h2821::server_set_mac_handler(const std::string& response)
{
    std::cout << ">>> server_set_mac_handler >>>" << response << std::endl;

    return 0;
}

//接收到 +SETNAME
int bearpi_h2821::server_set_name_handler(const std::string& response)
{
    std::cout << ">>> server_set_name_handler >>>" << response << std::endl;

    return 0;
}

//接收到启动服务
int bearpi_h2821::server_start_service_handler(const std::string& response)
{
    std::cout << ">>> server_start_service_handler >>>" << response << std::endl;

    return 0;
}

//服务端获取用户连接列表
int bearpi_h2821::server_get_client_list_handler(const std::string& response)
{
    std::cout << ">>> server_get_client_list_handler >>>" << response << std::endl;

    return 0;
}

//服务端向指定客户端发送数据
int bearpi_h2821::server_send_data_handler(const std::string& response)
{
    std::cout << ">>> server_send_data_handler >>>" << response << std::endl;

    return 0;
}

//服务端线程
void bearpi_h2821::server_thread_handler()
{
    bool running = true;
    static unsigned int count = 0;
    while(running)
    {

//        std::unique_lock<std::mutex> lock(srv_recv_mtx);    //获取服务端数据接收互斥锁
        
//        srv_cv.wait(lock, [this]() { return !srv_recv_queue.empty();});    //等待条件成立

//        if (!running) break;

//        //在这里发送通知到应用层
//        std::string msg = srv_recv_queue.front(); // 获取消息
//        srv_recv_queue.pop(); // 从队列中移除消息

//        lock.unlock(); // 解锁以允许其他线程访问队列

        //std::cout << ">>> server_thread_handler running >>> msg is " << ++count << msg << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
}  

 //启动服务器模式（外部函数接口）
int bearpi_h2821::h2821_start_server()
{
    //std::cout << "h2821_start_server" << std::endl;
    //在这里读取配置参数
    const std::string mac_str = "0A1B2C3D4E5F";
    const std::string server_name = "SLE_SERVER";

    //
    if (client_thread.joinable()) client_thread.join();    //如果客户端模式正在运行，先停止

    at_parser->add_command_handler(("OK"), server_ok_handler);
    at_parser->add_command_handler(("+SRECVDATA:"),server_recv_process);
    at_parser->add_command_handler(("+SETMODE:"),server_set_mode_handler);
    at_parser->add_command_handler(("+SETSLEADDR:"),server_set_mac_handler);
    at_parser->add_command_handler(("+SSETNAME:"),server_set_name_handler);
    at_parser->add_command_handler(("+SSERVER"),server_start_service_handler);
    at_parser->add_command_handler(("+SCLIST"),server_get_client_list_handler);
    at_parser->add_command_handler(("+SSEND"),server_send_data_handler);
    at_parser->add_command_handler(("+SSENDALL"),server_send_data_handler);

    at_parser->start();

    this->at_cmd();
    this->at_set_mode(1);    //设置服务端模式
    this->at_set_mac(mac_str);    //设置mac地址
    this->at_s_set_name(server_name);    //设置服务端名字
    this->at_start_server(0,0,"");    //关闭服务端
    this->at_start_server(1,0,"");    //启动服务端

    server_thread = std::thread(&bearpi_h2821::server_thread_handler, this);    //启动服务端线程

    return 0;
}   



//外部通过轮询方式获取数据（外部函数接口）
int bearpi_h2821::server_recv_data_poll(std::string& data)
{
    int data_size = 0;
    //std::cout << ">>> server_recv_data_poll running >>>" << std::endl;

    std::unique_lock<std::mutex> lock(srv_recv_mtx);    //获取服务端数据接收互斥锁

    if(!srv_recv_queue.empty())    //队列非空
    {
        data = srv_recv_queue.front(); // 获取消息
        data_size = static_cast<int>(data.size());
        srv_recv_queue.pop(); // 从队列中移除消息
    }

    lock.unlock(); // 解锁以允许其他线程访问队列

    return data_size;
}   

//向指定客户端发送数据（外部函数接口）
int bearpi_h2821::server_send_data(std::string& client_id, std::string& data)
{
    int send_len = 0;

    if(data.size())send_len = at_s_send_data(client_id, data);

    return send_len;
}

//向所有客户端发送数据（外部函数接口）
int bearpi_h2821::server_send_data(std::string& data)
{
    int send_len = 0;

    if(data.size())send_len = at_s_send_data(data);

    return send_len;
}




















/**
 *  以下是客户端相关函数
 * 
 * 
 * 
 * 
 * */

//设置客户端名字
int bearpi_h2821::at_c_set_name(const std::string& name)
{
    if(nullptr == at_parser)return -1;
    if(name.empty())return -1;

    std::string cmd = "AT+CSETNAME=" + name;

    at_parser->send_at_cmd(cmd);

    return 0;
}

//客户端开始连接
int bearpi_h2821::at_client_connect(const std::string& srv_name, int encry_type, const std::string& secret_key)
{
    if(nullptr == at_parser)return -1;

    std::string cmd;

    if((encry_type >= 0) && (!secret_key.empty()))
    {
        if(encry_type == 0)cmd = "AT+CCONNECT=" + srv_name + ",0," + secret_key;
        else cmd = "AT+CCONNECT=" + srv_name + ",1," + secret_key;
    }
    else
    {
        cmd = "AT+CCONNECT=" + srv_name;
    }

    at_parser->send_at_cmd(cmd);
    return 0;
}   


//客户端线程
void bearpi_h2821::client_thread_handler()
{
    bool running = true;

    while(running)
    {
        std::cout << ">>> client_thread_handler running >>>" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    }
}   

//静态函数，用户AT指令回调
int bearpi_h2821::client_ok_handler(const std::string& response)
{
    std::cout << ">>> client_ok_handler >>>" << response << std::endl;

    return 0;
}

int bearpi_h2821::client_recv_process(const std::string& response)
{
    std::cout << ">>> client_recv_process >>>" << response << std::endl;

    return 0;
}

int bearpi_h2821::client_set_mode_handler(const std::string& response)
{
    std::cout << ">>> client_set_mode_handler >>>" << response << std::endl;

    return 0;
}

int bearpi_h2821::client_set_mac_handler(const std::string& response)
{
    std::cout << ">>> client_set_mac_handler >>>" << response << std::endl;

    return 0;
}

int bearpi_h2821::client_set_name_handler(const std::string& response)
{
    std::cout << ">>> client_set_name_handler >>>" << response << std::endl;

    return 0;
}

int bearpi_h2821::client_connect_handler(const std::string& response)
{
    std::cout << ">>> client_connect_handler >>>" << response << std::endl;

    return 0;
}


//启动客户端模式
int bearpi_h2821::h2821_start_client()
{
    //在这里读取配置参数
    const std::string mac_str = "0A1B2C3D4E5F";
    const std::string client_name = "SLE_CLIENT_1";
    const std::string srv_name = "SLE_SERVER";
    //
    if (server_thread.joinable()) server_thread.join();    //如果客户端模式正在运行，先停止

    at_parser->add_command_handler(("OK"), client_ok_handler);
    at_parser->add_command_handler(("+CRECVDATA:"),client_recv_process);
    at_parser->add_command_handler(("+SETMODE:"),client_set_mode_handler);
    at_parser->add_command_handler(("+SETSLEADDR:"),client_set_mac_handler);
    at_parser->add_command_handler(("+CSETNAME:"),client_set_name_handler);
    at_parser->add_command_handler(("+SSERVER"),server_start_service_handler);

    at_parser->start();

    this->at_set_mode(0);    //设置客户端模式
    this->at_set_mac(mac_str);
    this->at_s_set_name(client_name);    //设置客户端名字
    this->at_client_connect(srv_name, -1, "");    //启动服务端

    client_thread = std::thread(&bearpi_h2821::client_thread_handler, this);    //启动服务端线程

    return 0;
}    

//客户端通过轮询方式获取数据
int bearpi_h2821::client_recv_data_poll(std::string& data)
{

}

//客户端发送数据
int bearpi_h2821::client_send_data(std::string& data)
{

}

